package com.hdjk.view.fragment.main;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.holder.Holder;
import com.bigkoo.convenientbanner.listener.OnItemClickListener;
import com.hdjk.view.R;
import com.hdjk.view.activity.financial.CustomFundListActivity;
import com.hdjk.view.activity.financial.FinancialListActivity;
import com.hdjk.view.activity.financial.FundListActivity;
import com.hdjk.view.activity.main.WebBrowseActivity;
import com.hdjk.view.callback.CallBackListener;
import com.hdjk.view.config.Constant;
import com.hdjk.view.entity.BannerEntity;
import com.hdjk.view.network.Network;
import com.hdjk.view.util.UserTokenUtil;
import com.lst.projectlib.base.BaseFram;
import com.lst.projectlib.entity.Msg;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * 理财Fragment
 * Created by sxy on 2017/11/1.
 */

public class FinancialFragment extends BaseFram implements OnItemClickListener {
    private ArrayList<Integer> localImages = new ArrayList<>();
    private List<BannerEntity> mList;
    private CBViewHolderCreator<NetworkImageHolderView> mHolder;
    protected boolean isCreate = false;

    // Content View Elements
    private com.bigkoo.convenientbanner.ConvenientBanner cb_banner;
    private LinearLayout lin_financial;
    private TextView tv_financial_title;
    private TextView tv_financial_content;
    private TextView tv_financial_click;
    private LinearLayout lin_fund;
    private TextView tv_fund_title;
    private TextView tv_fund_content;
    private TextView tv_fund_click;
    private TextView tv_custom_fund_click;
    // End Of Content View Elements

    private void bindViews(View view) {
        cb_banner = (com.bigkoo.convenientbanner.ConvenientBanner) view.findViewById(R.id.cb_banner);
        lin_financial = (LinearLayout) view.findViewById(R.id.lin_financial);
        tv_financial_title = (TextView) view.findViewById(R.id.tv_financial_title);
        tv_financial_content = (TextView) view.findViewById(R.id.tv_financial_content);
        tv_financial_click = (TextView) view.findViewById(R.id.tv_financial_click);
        lin_fund = (LinearLayout) view.findViewById(R.id.lin_fund);
        tv_fund_title = (TextView) view.findViewById(R.id.tv_fund_title);
        tv_fund_content = (TextView) view.findViewById(R.id.tv_fund_content);
        tv_fund_click = (TextView) view.findViewById(R.id.tv_fund_click);
        tv_custom_fund_click = (TextView) view.findViewById(R.id.tv_custom_fund_click);
    }


    @Override
    protected View initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_financial, container, false);
        bindViews(view);
        isCreate = true;
        DisplayMetrics dm = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
        ViewGroup.LayoutParams layoutParams = cb_banner.getLayoutParams();
        layoutParams.width = dm.widthPixels;
        layoutParams.height = dm.widthPixels/2;
        cb_banner.setLayoutParams(layoutParams);
        return view;
    }

    @Override
    protected void initData() {
        mList = new ArrayList<>();
//        initBanner();
        setListener();
    }

    private void setListener() {
        tv_fund_click.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), FundListActivity.class);
                startActivity(intent);
            }
        });
        tv_financial_click.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), FinancialListActivity.class);
                startActivity(intent);
            }
        });
        tv_custom_fund_click.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), CustomFundListActivity.class);
                startActivity(intent);
            }
        });
    }

    private void initBanner() {
        mDialog.show();
        Network.getBannerList(UserTokenUtil.getToken(getContext()), new CallBackListener() {
            @Override
            public void onCallBackCompleted(Msg msg) {
                mDialog.dismiss();
                if (msg != null && msg.getSuccess() && msg.getData() != null && msg.getData() instanceof List) {
                    mList = (List<BannerEntity>) msg.getData();
                    List<String> images = new ArrayList<>();
                    for (int i = 0; i < mList.size(); i++) {
                        images.add(mList.get(i).getValue());
                    }
                    mHolder = new CBViewHolderCreator<NetworkImageHolderView>() {
                        @Override
                        public NetworkImageHolderView createHolder() {
                            return new NetworkImageHolderView();
                        }
                    };
                    cb_banner.setPages(mHolder, images) //设置两个点图片作为翻页指示器，不设置则没有指示器，可以根据自己需求自行配合自己的指示器,不需要圆点指示器可用不设
                            .setPageIndicator(new int[]{R.drawable.ic_page_indicator, R.drawable.ic_page_indicator_focused})
                            //设置指示器的方向
//                .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.ALIGN_PARENT_RIGHT)
//                .setOnPageChangeListener(this)//监听翻页事件
                            .setOnItemClickListener(FinancialFragment.this);
                }
            }

            @Override
            public void onCallBackError(Msg msg) {
                mDialog.cancel();
            }
        });
//        for (int position = 0; position < 7; position++)
//            localImages.add(getResId("ic_test_" + position, R.drawable.class));
//        cb_banner.setPages(
//                new CBViewHolderCreator<LocalImageHolderView>() {
//                    @Override
//                    public LocalImageHolderView createHolder() {
//                        return new LocalImageHolderView();
//                    }
//                }, localImages)
//                //设置两个点图片作为翻页指示器，不设置则没有指示器，可以根据自己需求自行配合自己的指示器,不需要圆点指示器可用不设
//                .setPageIndicator(new int[]{R.drawable.ic_page_indicator, R.drawable.ic_page_indicator_focused})
//                //设置指示器的方向
////                .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.ALIGN_PARENT_RIGHT)
////                .setOnPageChangeListener(this)//监听翻页事件
//                .setOnItemClickListener(this);
    }

    /**
     * 通过文件名获取资源id 例子：getResId("icon", R.drawable.class);
     *
     * @param variableName
     * @param c
     * @return
     */
    public static int getResId(String variableName, Class<?> c) {
        try {
            Field idField = c.getDeclaredField(variableName);
            return idField.getInt(idField);
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }
    }

    /**
     * 是否显示当前页
     * @param isVisibleToUser
     */
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isCreate) {//fragment是否创建
            if (isVisibleToUser) {
                if (mList == null || mList.size() < 1) {
                    initBanner();
                }
                if (!cb_banner.isTurning())
                    //开始自动翻页
                    cb_banner.startTurning(5000);
            } else {
                if (cb_banner.isTurning())
                    cb_banner.stopTurning();
            }
        }
    }

    // 开始自动翻页
    @Override
    public void onResume() {
        super.onResume();
        if (!cb_banner.isTurning())
            //开始自动翻页
            cb_banner.startTurning(5000);
    }

    // 停止自动翻页
    @Override
    public void onPause() {
        super.onPause();
        if (cb_banner.isTurning())
            //停止翻页
            cb_banner.stopTurning();
    }

    @Override
    public void onItemClick(int position) {
        BannerEntity entity=mList.get(position);
        if (entity.getValue2()!=null){
            Intent intent;
            switch (entity.getValue2()){
                case "1":
                    intent = new Intent(getContext(), WebBrowseActivity.class);
                    intent.putExtra("title", entity.getName());
                    intent.putExtra("url", Constant.URL_PORT+entity.getValue3());
                    startActivity(intent);
                    break;
            }
        }
    }

    /**
     * 网络图片加载
     */
    class NetworkImageHolderView implements Holder<String> {
        private ImageView imageView;

        @Override
        public View createView(Context context) {
            //你可以通过layout文件来创建，也可以像我一样用代码创建，不一定是Image，任何控件都可以进行翻页
            imageView = new ImageView(context);
            imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
            return imageView;
        }

        @Override
        public void UpdateUI(Context context, int position, String data) {
            ImageLoader.getInstance().displayImage(Constant.URL_PORT + data, imageView);
        }
    }

    /**
     * 本地图片加载
     */
    class LocalImageHolderView implements Holder<Integer> {
        private ImageView imageView;

        @Override
        public View createView(Context context) {
            imageView = new ImageView(context);
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            return imageView;
        }

        @Override
        public void UpdateUI(Context context, int position, Integer data) {
            imageView.setImageResource(data);
        }
    }
}
